package com.easystudy.media.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import com.easystudy.media.call.Callback;
import com.easystudy.media.conf.MediaConfig;
import com.easystudy.media.error.ErrorCode;
import com.easystudy.media.error.ReturnValue;
import com.easystudy.media.model.DeviceInfo;
import com.easystudy.media.model.StrategyInfo;
import com.easystudy.media.service.MediaService;
import com.easystudy.media.util.JsonUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @文件名称: AiServiceImpl.java
 * @功能描述: 媒体接入服务实现类
 * @版权信息: www.easystudy.com
 * @技术交流: 961179337(QQ群)
 * @编写作者: lixx2048@163.com
 * @联系方式: 941415509(QQ)
 * @开发日期: 2023年11月20日
 * @历史版本: V1.0
 * @备注信息:
 */
@Slf4j
@Service
public class MediaServiceImpl implements MediaService {
	/**
	 * 地址配置
	 */
	@Autowired
	private MediaConfig mediaConfig;
	/**
	 * 请求案例
	 */
	@Autowired
	private RestTemplate restTemplate;
	/**
	 * 报警回调
	 */
	private Callback callback;

	@Override
	public void register(Callback callback) {
		this.callback = callback;
	}

	@Override
	public Callback getCallback() {
		return this.callback;
	}

	@Override
	public ReturnValue<String> addDevice(DeviceInfo device) {
		// 设置请求头
		HttpHeaders headers = new HttpHeaders();
		headers.set("Authorization", "Bearer " + mediaConfig.getToken());
		MediaType type = MediaType.APPLICATION_JSON;
		headers.setContentType(type);

		// 错误处理
		restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
			@Override
			public void handleError(ClientHttpResponse response) throws java.io.IOException {
				log.error("添加媒体接入设备错误: {}", response.getStatusCode());
				super.handleError(response);
			}
		});

		// 请求数据
		String url = mediaConfig.getUrl() + "/media/addDevice";
		HttpEntity<String> entity = new HttpEntity<String>(JsonUtil.toJson(device), headers);
		ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

		// 获取请求结果
		String desc = response.getBody();
		if (!desc.equals("success")) {
			return new ReturnValue<String>(ErrorCode.ERROR_SERVER_ERROR, desc);
		}

		// 设备添加成功
		return new ReturnValue<String>();
	}
	

	@Override
	public ReturnValue<String> setStrategy(StrategyInfo strategy) {
		// 设置请求头
		HttpHeaders headers = new HttpHeaders();
		headers.set("Authorization", "Bearer " + mediaConfig.getToken());
		MediaType type = MediaType.APPLICATION_JSON;
		headers.setContentType(type);

		// 错误处理
		restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
			@Override
			public void handleError(ClientHttpResponse response) throws java.io.IOException {
				log.error("更新设备{}录像策略错误: {}", strategy.getDeviceId(), response.getStatusCode());
				super.handleError(response);
			}
		});

		// 请求数据
		String url = mediaConfig.getUrl() + "/media/updateStrategy";
		HttpEntity<String> entity = new HttpEntity<String>(JsonUtil.toJson(strategy), headers);
		ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

		// 获取请求结果
		String desc = response.getBody();
		if (!desc.equals("success")) {
			return new ReturnValue<String>(ErrorCode.ERROR_SERVER_ERROR, desc);
		}

		// 设置设备策略成功
		return new ReturnValue<String>();
	}
	
	@Override
	public ReturnValue<String> delDevice(String deviceId) {
		// 设置请求头
		HttpHeaders headers = new HttpHeaders();
		headers.set("Authorization", "Bearer " + mediaConfig.getToken());
		MediaType type = MediaType.APPLICATION_JSON;
		headers.setContentType(type);

		// 错误处理
		restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
			@Override
			public void handleError(ClientHttpResponse response) throws java.io.IOException {
				log.error("从媒体接入服务删除设备{}错误: {}", deviceId, response.getStatusCode());
				super.handleError(response);
			}
		});

		String url = mediaConfig.getUrl() + "/media/delDevice?deviceId=" + deviceId;
		HttpEntity<String> entity = new HttpEntity<String>(headers);
		ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
		if (response.getStatusCode() != HttpStatus.OK) {
			return new ReturnValue<String>(ErrorCode.ERROR_SERVER_ERROR, response.getBody());
		}
		
		// 获取请求结果
		String desc = response.getBody();
		if (!desc.equals("success")) {
			return new ReturnValue<String>(ErrorCode.ERROR_SERVER_ERROR, desc);
		}
		return new ReturnValue<String>();
	}

	@Override
	public ReturnValue<String> play(String deviceId, Integer channel, Integer stream) {
		// 设置请求头
		HttpHeaders headers = new HttpHeaders();
		headers.set("Authorization", "Bearer " + mediaConfig.getToken());
		MediaType type = MediaType.APPLICATION_JSON;
		headers.setContentType(type);

		// 错误处理
		restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
			@Override
			public void handleError(ClientHttpResponse response) throws java.io.IOException {
				log.error("点播媒体服务器视频{}错误: {}", deviceId, response.getStatusCode());
				super.handleError(response);
			}
		});

		String url = mediaConfig.getUrl() + "/media/play?deviceId=" + deviceId + "&channel=" + channel + "&stream=" + stream;
		HttpEntity<String> entity = new HttpEntity<String>(headers);
		ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
		if (response.getStatusCode() != HttpStatus.OK) {
			return new ReturnValue<String>(ErrorCode.ERROR_SERVER_ERROR, response.getBody());
		}
		
		String result = response.getBody();
		if (result.equals("failed")) {
			return new ReturnValue<String>(ErrorCode.ERROR_SERVER_ERROR, result);
		}
		
		// http://192.168.8.19:180/hls/001/1/1/index.m3u8
		return new ReturnValue<String>(result);
	}

	@Override
	public ReturnValue<String> stop(String deviceId, Integer channel, Integer stream) {
		// 设置请求头
		HttpHeaders headers = new HttpHeaders();
		headers.set("Authorization", "Bearer " + mediaConfig.getToken());
		MediaType type = MediaType.APPLICATION_JSON;
		headers.setContentType(type);

		// 错误处理
		restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
			@Override
			public void handleError(ClientHttpResponse response) throws java.io.IOException {
				log.error("停止媒体服务器视频{}错误: {}", deviceId, response.getStatusCode());
				super.handleError(response);
			}
		});

		String url = mediaConfig.getUrl() + "/media/stop?deviceId=" + deviceId + "&channel=" + channel + "&stream=" + stream;
		HttpEntity<String> entity = new HttpEntity<String>(headers);
		ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
		if (response.getStatusCode() != HttpStatus.OK) {
			return new ReturnValue<String>(ErrorCode.ERROR_SERVER_ERROR, response.getBody());
		}
		
		String result = response.getBody();
		if (!result.equals("success")) {
			return new ReturnValue<String>(ErrorCode.ERROR_SERVER_ERROR, result);
		}
		
		return new ReturnValue<String>();
	}
}
